import { getDvaApp } from 'umi';
import _ from 'lodash';
import { message } from 'antd';
import { formatMessage as text } from 'umi';

// 获取store
export function getStore() {
  return getDvaApp()._store;
}

// 获取dva数据
export function getState() {
  return getDvaApp()._store.getState();
}

// 国际化前缀函数
export function createAddPrefixFunc(prefix) {
  var func = key => prefix + key;
  return func;
}

/**
 * 跨应用路由跳转
 * @param {String} href url地址
 * @param {Object} stateObj 状态参数 可以通过history.state读取
 * @param {String} title 标题 暂时没有用
 */
export function routerGo(href = '/', title = null, stateObj = {}) {
  window.history.pushState(stateObj, title, href);
}

export let waitTime = (time = 100) => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

// 获取顶层对象
export var getGlobal = function() {
  if (typeof self !== 'undefined') {
    return self;
  }
  if (typeof window !== 'undefined') {
    return window;
  }
  if (typeof global !== 'undefined') {
    return global;
  }
  throw new Error('unable to locate global object');
};


// 验证权限
export function authorityVerify(key,isShowMessage=true) {
  var { user } = getState();
  var authority = user.authority;
  var rs = false;
  if (authority.indexOf(key) != -1) rs = true;
  // text:无权限操作
  if (!rs&&isShowMessage) message.warning(text({id:`global.noAuthority`}));
  return rs;
}

// 空闲执行
export function leisure(fn){
  if ('requestIdleCallback' in window) {
    // 使用原生的 requestIdleCallback
    requestIdleCallback(function(deadline) {
      fn()
    });
  } else {
    setTimeout(function() {
      fn()
    }, 0);
  }
}